package com.starbaba.system.menu.view;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.common.ResultJson;
import com.starbaba.controllog.aop.LogAble;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.hibernate.QueryType;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.core.web.tree.TreeBuilder;
import com.starbaba.system.menu.dao.MenuStrategy;
import com.starbaba.system.menu.model.MenuModel;
import com.starbaba.system.menu.model.MenuVO;
import com.starbaba.system.menu.service.MenuService;

@SuppressWarnings({"serial","rawtypes","unchecked"})
public class MenuAction extends BaseAction implements ModelDriven {
	@Resource(name = "MenuServiceImpl")
	private MenuService service;
	private MenuModel model;
	private ArrayList<ControlLogCategory> logCategorysArrayList;

	public MenuAction() {
		super.voClass = MenuVO.class;
		super.pkNameArray = new String[] { "menuId" };
		logCategorysArrayList = new ArrayList<ControlLogCategory>();
	}

	public String menumgr() {
		return Action.SUCCESS;
	}

	public String sort() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			MenuListVO listVO = new MenuListVO();
			listVO.setOrderBy("order asc, menuId");
			listVO.setOrder("asc");
			String MenuId = (String) getParamsMap().get("menuId");
			listVO.set_seq_parentMenuId(MenuId);
			this.setParamsMapToTargetObject(paramsMap, listVO);
			listVO.setFindAll(true);
			page = this.getService().doQuery(voClass, listVO);
			if (page.getDatas().size() > 0) {
				this.setIsEditAble(true);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addActionMessage(ex.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}

	/**
	 * 菜单管理树
	 * 
	 * @return
	 */
	public String tree() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			MenuListVO listVO = new MenuListVO();
			listVO.setOrderBy("order asc, menuId");
			listVO.setOrder("asc");
			this.setParamsMapToTargetObject(paramsMap, listVO);
			listVO.setFindAll(true);
			page = this.getService().doQuery(voClass, listVO);

			StringBuffer treeXML = this.buildMenuTree(page.getDatas());
			Struts2Utils.getRequest().setAttribute("treeXML", treeXML.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addActionMessage(ex.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}

	@Override
	public String save() {
		try {
			paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
			String isNew = (String) paramsMap.get(WebConstants.PAGE_ATTRIBUTE_ISNEW);
			this.setParamsMapToTargetObject(paramsMap, this.getEntityVO());
			MenuVO menuVO = (MenuVO) this.getEntityVO();
			MenuStrategy strategy = new MenuStrategy(menuVO, this.getUserVO());
			if (WebConstants.STRING_TRUE.equals(isNew)) {
				strategy.setIsnew(true);
			} else {
				strategy.setIsnew(false);
			}
			menuVO = (MenuVO) this.getService().doProcess(strategy);
			this.setTargetObjectToParamsMap(menuVO, paramsMap);
			this.setIsEditAble(false);
			this.setIsNew(false);
			this.addMessage("操作成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			this.addErrorMessage("操作失败,失败原因:" + ex.getMessage());
			return Action.ERROR;
		}
		return Action.SUCCESS;
	}

	@Override
	public void beforeAdd() {
		MenuVO menuVO = new MenuVO();
		menuVO.setPcontrolid((String) paramsMap.get("menuId"));
		paramsMap.clear();
		this.setEntityVO(menuVO);
	}

	@Override
	public void beforeList() {
		MenuListVO listVO = new MenuListVO();
		listVO.setFindAll(true);
		this.setEntityListVO(listVO);
	}

	/**
	 * 查询全部菜单数
	 * 
	 * @return
	 * @throws Exception
	 */
	public List getChildMenuListByParentMenuId(String menuId) throws Exception {
		MenuListVO listVO = new MenuListVO();
		listVO.setFindAll(true);
		listVO.setOrder(" parentMenuId ");
		page = this.getService().doQuery(MenuVO.class, listVO, QueryType.DATA);
		if (page.hasDatas()) {
			return page.getDatas();
		}
		return new ArrayList();
	}

	public StringBuffer buildMenuTree(List menuList) throws Exception {
		String nodeIdProperty = "menuId";
		String parentNodeIdProperty = "parentMenuId";
		String nodeNameProperty = "name";
		String pkNameProperty = "menuId";
		StringBuffer treeXML = TreeBuilder.buildTreeXML(menuList, nodeIdProperty, nodeNameProperty,
				parentNodeIdProperty, pkNameProperty, null);
		return treeXML;
	}

	/**
	 * 
	 * @Title: menuList
	 * @Description: 【菜单列表】
	 * @param
	 * @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	public void menuList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String menutype = (String) paramsMap.get("menutype");
		String menustatus = (String) paramsMap.get("menustatus");
		String menuname = (String) paramsMap.get("menuname");
		if (null != menutype) {
			model.setMenutype(menutype);
		}
		if (null != menustatus) {
			model.setStatus(menustatus);
		}
		if (null != menuname) {
			model.setLname(menuname);
		}
		parsePageRequest();
		try {
			PageResponse pageResponse = new PageResponse();
			List list = service.getDataList(pageRequest.getIDisplayStart(), pageRequest.getIDisplayLength(), model,
					pageResponse, getService());
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			String jsonStr = JsonUtils.toJson(pageResponse, null, true, null, false);
			sendJsonMessage(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title: addMenu
	 * @Description: 【新增菜单】
	 * @param
	 * @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	@LogAble(operate = LogAble.OPERATE_ADD)
	public void addMenu() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String addmenuname = (String) paramsMap.get("addmenuname");
		String addurl = (String) paramsMap.get("addurl");
		String addmenutype = (String) paramsMap.get("addmenutype");
		String addpcontrolid = (String) paramsMap.get("addpcontrolid");// 父id
		String creator = (String) paramsMap.get("creator");
		java.util.Date currentTime = new Date();
		// 拼接controlid
		String controlid = addpcontrolid;
		Object obj = this.getService().findUniqueByHQL(
				"select max(vo.controlid) from MenuVO as vo where vo.pcontrolid = ? order by vo.controlid asc",
				new Object[] { addpcontrolid });
		if (obj == null) {
			controlid += "01";
		} else {
			// 如果controlid="0012",先把controlid转成int,再转成string,获取00的长度再插入
			String objString = String.valueOf(obj);
			Long objint = Long.valueOf(objString);
			String objString1 = String.valueOf(objint);
			String zeroString = "";
			if (objString.length() - objString1.length() == 0) {
				controlid = String.valueOf(objint + 1);
			} else {
				Integer zeroint = objString.length() - objString1.length();
				for (Integer i = 0; i < zeroint; i++) {
					zeroString += '0';
				}
				controlid = zeroString + String.valueOf(objint + 1);
			}

		}
		try {
			// 插入到user表
			MenuVO entity = new MenuVO();
			entity.setLname(addmenuname);
			entity.setUrl(addurl);
			entity.setMenutype(addmenutype);
			entity.setPcontrolid(addpcontrolid);
			entity.setCreator(creator);
			entity.setLasteditor(creator);
			entity.setCreatetime(currentTime);
			entity.setLasttime(currentTime);
			// 新增账户时默认设置为有效
			entity.setStatus("1");
			entity.setType("0");
			entity.setControlid(controlid);

			this.getService().doCreate(MenuVO.class, entity);
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "新增成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(controlid);
			logCategory.setName(addmenuname);
			logCategorysArrayList.add(logCategory);

		} catch (Exception e) {
			sendErrMsg(e.getMessage());
			LogService.error(e);
		}
	}

	@LogAble(operate = LogAble.OPERATE_MODIFY)
	public void changeMenu() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String addmenuname = (String) paramsMap.get("changemenuname");
		String addurl = (String) paramsMap.get("changeurl");
		String pid = (String) paramsMap.get("pid");
		String creator = (String) paramsMap.get("creator");
		String menutype = (String) paramsMap.get("menutype");
		String id = (String) paramsMap.get("id");
		java.util.Date currentTime = new Date();
		addurl = (addurl == "null" ? null : addurl);
		// 递归修改子菜单的 menutype
		service.updateRecursion(id, menutype);
		try {
			this.getService()
					.executeHQLUpdate(
							" update MenuVO as vo set vo.lname = ?, vo.url = ?, vo.lasteditor = ?, vo.lasttime = ?,vo.menutype=?,vo.pcontrolid=? where vo.controlid = ? ",
							new Object[] { addmenuname, addurl, creator, currentTime, menutype, pid, id });
			JsonObject result = new JsonObject();
			ResultJson resultJs = new ResultJson();
			resultJs.msg = "新增成功";
			result.add("result", resultJs.toJSON());
			sendJsonMessage(result.toString());

			ControlLogCategory logCategory = new ControlLogCategory();
			logCategory.setId(id);
			logCategory.setName(addmenuname);
			logCategorysArrayList.add(logCategory);

		} catch (Exception e) {
			sendErrMsg(e.getMessage());
		}

	}

	public void getNum() {
		int n = service.getNum();
		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = n + "";
		result.add("result", resultJs.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void sendErrMsg(String msg) {
		JsonObject result = new JsonObject();
		ResultJson resultJs = new ResultJson();
		resultJs.msg = msg;
		result.add("result", resultJs.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getActionId() {
		return "1000000803";
	}

	@Override
	public Object getModel() {
		if (model == null) {
			model = new MenuModel();
		}
		return model;
	}
}
